package com.supermarket.interceptor;


import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;

public class LoginInterceptor implements HandlerInterceptor {

    private HashSet<String> whiteUrls = new HashSet<>();

    public LoginInterceptor(){
        //添加一些不拦截的路径
        //whiteUrls.add("/index.html");
        whiteUrls.add("/login.html");
        //whiteUrls.add("/admin/login");
        //whiteUrls.add("/captcha/createCaptcha");
    }

    //访问目标路径之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");

        //获取请求路径
        String requestURI = request.getRequestURI();//login.html
        String requestURL = request.getRequestURI().toString();//http://localhost:8080/login.html

        //遍历
        for (String url : whiteUrls){

            //判断
            if (requestURI.contains(url)){

                return true;
            }
        }

        //判断当前用户是不是已经登录过了
        if (request.getSession().getAttribute("admin")!=null){

            return true;
        }else{

            response.sendRedirect(request.getContextPath()+"/login.html");

            return false;

        }


        //return true;//true表示放行，false表示终止
    }

    //访问目标路径之后执行
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle");
//    }

    //最后执行
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("afterCompletion");
//    }
}
